<template>
  <div>
    <TodoTitle />
    <TodoInput @add-todo="handleAddTodo"/>
    <div class="container mt-3">
      <article class="panel is-primary has-background-success-light">
        <p class="panel-heading">
          未完成
          <span class="tag is-light">{{ unFinishLength }}</span>
        </p>
        <div class="panel-block columns is-multiline">
          <TodoItem
            v-for="todo in unFinishTodos"
            :key="`todo-${todo.id}`"
            :id="todo.id"
            :title="todo.title"
            :has-finish="todo.hasFinish"
            @toggle-finish="handleToggleFinish"
            @delete-todo="handleDeleteTodo"
          />
        </div>
      </article>
    </div>
    <div class="container ">
      <article class="panel is-info has-background-success-light">
        <p class="panel-heading">
          已完成
        <span class="tag is-light">{{ hasFinishLength }}</span>
        </p>
      <div class="panel-block columns is-multiline">
          <TodoItem
            v-for="todo in hasFinishTodos"
            :key="`todo-${todo.id}`"
            :id="todo.id"
            :title="todo.title"
            :has-finish="todo.hasFinish"
            @toggle-finish="handleToggleFinish"
            @delete-todo="handleDeleteTodo"
          />
        </div>
      </article>
    </div>
  </div>
</template>

<script>
import TodoTitle from './components/TodoTitle'
import TodoInput from './components/TodoInput'
import TodoItem from './components/TodoItem'

export default {
  data () {
    return {
      todos: [
        { id: 1, title: '吃饭', hasFinish: true },
        { id: 2, title: '睡觉', hasFinish: false },
        { id: 3, title: '打代码', hasFinish: true }
      ]
    }
  },
  methods: {
    handleAddTodo ({ title }) {
      if (title !== '') {
        this.todos.push({
          id: Date.now(),
          title,
          hasFinish: false
        })
      }
    },
    handleToggleFinish ({ id }) {
      this.todos = this.todos.map(todo => {
        if (todo.id === id) todo.hasFinish = !todo.hasFinish
        return todo
      })
    },
    handleDeleteTodo ({ id }) {
      this.todos = this.todos.filter(todo => todo.id !== id)
    }
  },
  components: {
    TodoTitle,
    TodoInput,
    TodoItem
  },
  computed: {
    hasFinishTodos () {
      return this.todos.filter(todo => todo.hasFinish)
    },
    unFinishTodos () {
      return this.todos.filter(todo => !todo.hasFinish)
    },
    hasFinishLength () {
      return this.hasFinishTodos.length
    },
    unFinishLength () {
      return this.unFinishTodos.length
    }
  }
}
</script>
